package com.onlyxiahui.aware.basic.util.recommend;

import java.util.List;
import java.util.stream.IntStream;

import com.google.common.collect.Lists;
import com.onlyxiahui.aware.basic.util.recommend.bean.ItemData;

/**
 * Description <br>
 * Date 2020-12-30 15:12:50<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class Algorithm {

	public double correlation(List<ItemData> xList, List<ItemData> yList) {
		List<Double> xs = Lists.newArrayList();
		List<Double> ys = Lists.newArrayList();
		xList.forEach(x -> {
			yList.forEach(y -> {
				if (x.getKey().equals(y.getKey())) {
					xs.add(x.getRate());
					ys.add(y.getRate());
				}
			});
		});
		return getRelate(xs, ys);
	}

	public Double getRelate(List<Double> xs, List<Double> ys) {
		int n = xs.size();
		double ex = xs.stream().mapToDouble(x -> x).sum();
		double ey = ys.stream().mapToDouble(y -> y).sum();

		double ex2 = xs.stream().mapToDouble(x -> Math.pow(x, 2)).sum();
		double ey2 = ys.stream().mapToDouble(y -> Math.pow(y, 2)).sum();

		double exy = IntStream.range(0, n).mapToDouble(i -> xs.get(i) * ys.get(i)).sum();
		double numerator = exy - ex * ey / n;
		double denominator = Math.sqrt((ex2 - Math.pow(ex, 2) / n) * (ey2 - Math.pow(ey, 2) / n));
		if (denominator == 0) {
			return 0.0;
		}
		return numerator / denominator;
	}
}
